﻿using System;

using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

using Application.UserApp;
using Demo.Models;
using Utility;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
using Domain;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Demo.Controllers
{
    public class LoginController : Controller
    {
        private IUserAppService _userAppService;
        public LoginController(IUserAppService userAppService)
        {
            _userAppService = userAppService;
        }
        [HttpGet]
        public IActionResult Index()
        {
           // var user = _userAppService.CheckUser("admin", "123456");
            return View();
        }
        [HttpPost]
        public IActionResult Index(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                User user = _userAppService.CheckUser(model.UserName,model.Password);
               
                if (user!=null)
                {
                    //记录Session
                    //HttpContext.Session.SetString("CurrentUserId",user.Id.ToString());
                    //HttpContext.Session.Set("CurrentUser", ByteConvertHelper.Object2Bytes(user));
                    user.AuthenticationType = "DefaultAuthenticationScheme";
                    var identity = new ClaimsIdentity(user);
                    identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
                    var principal = new ClaimsPrincipal(identity);
                    //是否记住登录信息
                    HttpContext.SignInAsync(DefaultAuthorizeAttribute.DefaultAuthenticationScheme, principal,
                        new AuthenticationProperties { IsPersistent = model.RememberMe });
                    //跳转到系统首页
                    return RedirectToAction("Index","Home");
                }
                ModelState.AddModelError("","用户名密码错误");
                return View();
            }
            return View(model);
        }
    }
}
